extends Spatial
const Item_select = preload("res://2d/item_select.tscn")

onready var npcs = $npcs
onready var talk = $ui/talk
onready var player = $player
onready var inventory = $inventory
onready var sale_window = $ui/sale_window
onready var date = $ui/date

func _ready():
	$player.connect("open_placement_ui", self, "open_placement_ui")
	$player.connect("open_seat_ui", self, "open_seat_ui")
	$ui/seat_menu.connect("open_shop", self, "open_shop")
	$ui/debug/HBoxContainer/VBoxContainer/generate_items.connect("pressed", inventory, "debug_generate")
	$ui/seat_menu.visible = false
	$ui/sale_window.visible = false
	$ui/talk.visible = false
	inventory.connect("money_changed", date, "on_money_changed")
	
	$next_shopper_timer.connect("timeout", self, "next_shopper")

func open_shop():
	var npcs = $npcs
	npcs.generate_shoppers()
	$next_shopper_timer.start()
	
func open_placement_ui(spot):
	var select_screen = Item_select.instance()
	select_screen.connect("item_selected", self, "place_item", [spot])
	add_child(select_screen)
	select_screen.open(inventory)
	G.in_ui = true
	
func place_item(item, spot):
	spot.place_item(item, inventory)
	G.in_ui = false

func open_seat_ui():
	$ui/seat_menu.open()

func next_shopper():
	var shopper = npcs.next_shopper()
	if shopper:
		if shopper.reason.type == "buy":
			var vars = {"item": shopper.reason.item.full_name()}
			var lines = shopper.lines("greeting")
			lines.append_array(shopper.lines("buy", vars))
			talk.open([player], [shopper], lines)
			talk.connect("finished", self, "open_sell_ui", [shopper])
			print("open item sale")
		elif shopper.reason.type == "sell":
			print("open item buying")
		elif shopper.reason.type == "request":
			var req = shopper.reason.request
			var vars = {"category": req["category"], "adjective":PoolStringArray(req["adjectives"]).join(" and ")}
			var line_type = "request"
			if req["category"]:
				line_type += "_category"
			if req["adjectives"]:
				line_type += "_adjective"
			var lines = shopper.lines("greeting")
			lines.append_array(shopper.lines(line_type, vars))
			talk.open([player], [shopper], lines)
			talk.connect("finished", self, "open_request_ui", [shopper, vars],CONNECT_ONESHOT)
		G.in_ui = true
		shopper.move_to_counter(player.body.get_global_transform().origin)
	else:
		G.in_ui = false
		$ui/date.advance(1)
		print("shoppers gone")
		
func full_inventory():
	var spots = get_tree().get_nodes_in_group("item_spot")
	return inventory.copy_merged_with_spots(spots)

func open_request_ui(shopper, vars):
	var select_screen = Item_select.instance()
	select_screen.connect("item_selected", self, "accept_item", [shopper])
	add_child(select_screen)
	select_screen.open(full_inventory())
	
func accept_item(item, shopper):
	var line_type = shopper.request_match_line(item, shopper.reason.request)
	var lines = shopper.lines(line_type)
	var accepted = (not ("_nothing" in line_type)) and (not ("_bad" in line_type))
	talk.open([player], [shopper], lines)
	if accepted:
		talk.connect("finished", self, "open_sell_ui", [item, shopper], CONNECT_ONESHOT)
	else:
		talk.connect("finished", self, "leave_outraged", [shopper], CONNECT_ONESHOT)

func open_sell_ui(item, shopper):
	$ui/sale_window.open(shopper, item)
	$ui/sale_window.connect("selected", self, "on_value_selected", [item, shopper], CONNECT_ONESHOT)
	
func on_value_selected(value, item, shopper, rehaggle_multiplier=1.0):
	var haggle_rating = shopper.haggle_rating(value, item.definition.base_value, "buy_price", rehaggle_multiplier)
	var accepted = "price_good" in haggle_rating
	var leaving = "_outrage" in haggle_rating
	var lines = shopper.lines(haggle_rating)
	talk.open([player], [shopper], lines)
	if accepted:
		talk.connect("finished", self, "on_item_sold", [item, value, shopper],CONNECT_ONESHOT)
	elif leaving:
		talk.connect("finished", self, "leave_outraged", [shopper], CONNECT_ONESHOT)
	elif shopper.attempt_rehaggle():
		talk.connect("finished", self, "rehaggle", [value,item, shopper, 0.5], CONNECT_ONESHOT)
	else:
		talk.connect("finished", self, "leave_outraged", [shopper], CONNECT_ONESHOT)
		
		
func rehaggle(value, item, shopper, multiplier):
	$ui/sale_window.open(shopper, item, true)
	$ui/sale_window.connect("selected", self, "on_value_selected", [item, shopper, multiplier], CONNECT_ONESHOT)

func on_item_sold(item, value, shopper):
	print("TODO item sold, remove it from inventory, add value")
	$next_shopper_timer.start()
	inventory.modify_money(value)
	if not inventory.lose_item(item.definition.id):
		lose_from_spot(item.definition.id)
	shopper.leave_through_door($map.door_position)
	pass

func lose_from_spot(id):
	var spots = get_tree().get_nodes_in_group("item_spot")
	for spot in spots:
		if spot.item and spot.item.definition.id == id:
			spot.place_item(null, null)
			return true
	return false

func leave_outraged(shopper):
	shopper.leave_through_door($map.door_position)
	$next_shopper_timer.start()
